

import os
import pygame
import ogg.vorbis
from ogg.vorbis import VorbisFile

from jukebox.Track import Track

class Album:

    def __init__(self, path):
        (a,b) = path.split('/')[-1].split('--')
        if b[:len(a)] == a:
            b = b[len(a):]
        self.name = ' '.join(a.split('-')).upper() + ':  ' + ' '.join(b.split('-'))
        self.tracks = []
        for track in os.listdir(path):
            try:
                int(track)
                self.tracks.append(Track(os.path.join(path,track),int(track)))
            except:
                pass
        self.tracks.sort()

        self.genre = None
        if os.path.exists(os.path.join(path,'.genre')):
            self.genre = open(os.path.join(path,'.genre'), 'r').read().strip().lower()
        else:
            try:
                try:
                    self.genre = str(VorbisFile(os.path.join(path,'001')).comment()['genre'][0])
                    self.type = 'long'
                except IOError:
                    try:
                                            # yeah, yeah total hack
                        self.genre = str(VorbisFile(os.path.join(path,'002')).comment()['genre'][0])
                        self.type = 'long'
                    except IOError:
                        self.genre = str(VorbisFile(os.path.join(path,'1')).comment()['genre'][0])
                        self.type = 'short'
            except ogg.vorbis.VorbisError:
                pass

        self.path = path
        self.x = 10
        self.y = 10

        self.art = None
        if os.path.isfile(os.path.join(self.path,'art.jpeg')):
            self.art = pygame.image.load(os.path.join(self.path,'art.jpeg'))

    def hasArtwork(self):
        return self.art is not None
    def artwork(self):
        return self.art


    # FIXME make this be a list
 
    def track(self,idx):
        if idx < 0 or idx >= len(self.tracks):
            return None
        return self.tracks[idx]
